//
//  SSStatusPicView.swift
//  MyMicroBlog
//
//  Created by stevenSu on 15/8/2.
//  Copyright © 2015年 stevenSu. All rights reserved.
//

import UIKit
import SDWebImage

class SSStatusPicView: UICollectionView {
    private let layoutMinimumSpacing: CGFloat = 5
    private let layoutItemSize: CGFloat = 90
    private let layoutItemMargin: CGFloat = 5
    private let layoutMaxCol = 3
    private let defaultPictureWidth: CGFloat = 150
    private let defaultPictureHeight: CGFloat = 120
    private let minimumPictureWidth: CGFloat = 40
    
    private let reuseID = "SSStatusPicCell"
    private let flowLayout = UICollectionViewFlowLayout()
    var status: SSStatus? {
        didSet {
            sizeToFit()
            reloadData()
        }
    }
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: flowLayout)
        flowLayout.minimumInteritemSpacing = layoutMinimumSpacing
        flowLayout.minimumLineSpacing = layoutMinimumSpacing
        flowLayout.sectionInset = UIEdgeInsetsZero
        dataSource = self
        delegate = self
        backgroundColor = UIColor.clearColor()
        registerClass(SSStatusPicCell.self, forCellWithReuseIdentifier: reuseID)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return setLayout()
    }
    
    private func setLayout() -> CGSize {
        let imgCount = status?.picURLS?.count ?? 0
        let itemSize = CGSize(width: layoutItemSize, height: layoutItemSize)
        let margin: CGFloat = layoutItemMargin
        let maxCol = layoutMaxCol
        flowLayout.itemSize = itemSize
        
        switch imgCount {
        case 0:
            return CGSizeZero
        case 1:
            let urlStr = status!.picURLS!.last!.absoluteString
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlStr) {
                var size = image.size
                size.width = size.width < minimumPictureWidth ? minimumPictureWidth : size.width
                size.width = size.width > UIScreen.mainScreen().bounds.width ? defaultPictureWidth : size.width
                flowLayout.itemSize = size
                return flowLayout.itemSize
            }
            
            let size = CGSize(width: defaultPictureWidth, height: defaultPictureHeight)
            flowLayout.itemSize = size
            return size
        case 4:
            let size = itemSize.width * 2 + margin
            return CGSize(width: size, height: size)
        
        // 2, 3, 5, 6, 7, 8 ,9
        default:
            let rows = (imgCount - 1) / maxCol + 1
            let w = itemSize.width * CGFloat(maxCol) + margin * CGFloat(maxCol - 1)
            let h = itemSize.height * CGFloat(rows) + margin * (CGFloat(rows) - 1)
            return CGSize(width: w, height: h)
        }
    }
    
    func cellScreenView(indexPath: NSIndexPath) -> CGRect {
        let cell = cellForItemAtIndexPath(indexPath)!
        let rect = convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
//        return frameCorrection(cell)
        return rect
    }
    // 修正函数，点击除indexPath(0,0)的cell都会有不明原因的偏移，直接用第一个cell的window绝对位置+偏移量来获取其他cell的绝对位置
//    func frameCorrection(cell: UICollectionViewCell) -> CGRect {
//        let baseCell = cellForItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0))!
//        var baseRect = baseCell.convertRect(baseCell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
//        // 修正公式
//        baseRect.origin.x += cell.frame.origin.x
//        baseRect.origin.y += cell.frame.origin.y
//        return baseRect
//        }
    
    func cellFullScreenView(indexPath: NSIndexPath) -> CGRect {
        let urlStr = status!.picURLS![indexPath.item].absoluteString
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlStr)
        
        let scale = image.size.height / image.size.width
        let screenSize = UIScreen.mainScreen().bounds.size
        let h = screenSize.width * scale
        
        var y: CGFloat = 0
        if h < screenSize.height {
            y = (screenSize.height - h) * 0.5
        }
        return CGRect(x: 0, y: y, width: screenSize.width, height: h)
    }
    
    class SSStatusPicCell: UICollectionViewCell {
        private var cellCountInCollectionView: Int? {
            didSet {
                imgView.contentMode = self.cellCountInCollectionView > 1 ? UIViewContentMode.ScaleAspectFill : UIViewContentMode.ScaleAspectFit
            }
        }
        
        private lazy var gifView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
        
        lazy var imgView: UIImageView =  {
            let view = UIImageView()
            //            view.contentMode = UIViewContentMode.ScaleAspectFill
            view.clipsToBounds = true
            return view
            }()
        var imgURL: NSURL? {
            didSet {
                imgView.sd_setImageWithURL(imgURL!)
                gifView.hidden = (imgURL!.absoluteString as NSString).pathExtension.lowercaseString != "gif" ? true : false
            }
        }
        override init(frame: CGRect) {
            super.init(frame: frame)
            setupUI()
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        private func setupUI() {
            contentView.addSubview(imgView)
            contentView.addSubview(gifView)
            imgView.ff_Fill(contentView)
            gifView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: contentView, size: nil)
        }
    }

}

let SSStatusPicViewDidSelectedNotification = "SSStatusPicViewDidSelectedNotification"
let SSStatusPicViewStatus = "SSStatusPicViewStatus"
let SSStatusPicViewStatusDidSelectedIndexPath = "SSStatusPicViewStatusDidSelectedIndexPath"
extension SSStatusPicView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.picURLS?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = dequeueReusableCellWithReuseIdentifier(reuseID, forIndexPath: indexPath) as! SSStatusPicCell
        cell.cellCountInCollectionView = status?.picURLS?.count
        cell.imgURL = status!.picURLS![indexPath.item]
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

        NSNotificationCenter.defaultCenter().postNotificationName(SSStatusPicViewDidSelectedNotification, object: self, userInfo: [SSStatusPicViewStatus: status!, SSStatusPicViewStatusDidSelectedIndexPath: indexPath])
        
    }
}
